package jp.eisbahn.mgapi.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * The utility class for the operation about I/O.
 * @author Yoichiro Tanaka
 */
public final class IOUtils {

    /** A size of a byte buffer. */
    private static final int BYTE_BUFFER_SIZE = 1024;

    /**
     * Initialize this instance.
     */
    private IOUtils() {
        super();
    }

    /**
     * Close the input stream without errors.
     * @param in The input stream.
     */
    public static void closeQuietly(final InputStream in) {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Close the output stream without errors.
     * @param out The output stream.
     */
    public static void closeQuietly(final OutputStream out) {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Close the reader without errors.
     * @param reader The reader object.
     */
    public static void closeQuietly(final Reader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Close the writer without errors.
     * @param writer The writer object.
     */
    public static void closeQuietly(final Writer writer) {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Copy contents from the input stream to the output stream.
     * @param in The content's source.
     * @param out The output stream.
     * @return The size copied.
     * @throws IOException If IOException occurred.
     */
    public static int copy(
            final InputStream in, final OutputStream out) throws IOException {
        byte[] buf = new byte[BYTE_BUFFER_SIZE];
        int result = 0;
        int size;
        while ((size = in.read(buf, 0, BYTE_BUFFER_SIZE)) != -1) {
            out.write(buf, 0, size);
            result += size;
        }
        return result;
    }

}
